import axios, { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse } from 'axios';
import { getStorage } from './index';

// 响应数据接口
interface ResponseData<T = any> {
  code: number;
  data: T;
  message: string;
}

// 环境变量类型声明
interface ImportMetaEnv {
  VITE_ENV: string;
  VITE_REQUEST_API: string;
  VITE_REQUEST_URL: string;
}

const { VITE_ENV, VITE_REQUEST_API, VITE_REQUEST_URL } = import.meta.env as unknown as ImportMetaEnv;

const service: AxiosInstance = axios.create({
  timeout: 1000 * 60 * 3,
  baseURL: VITE_ENV !== 'development' ? VITE_REQUEST_API : VITE_REQUEST_URL
});

// 请求拦截
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = getStorage({ key: 'test-token', islocal: true });
    config.headers['Authorization'] = `Bearer ${token}`;
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 响应拦截
service.interceptors.response.use(
  (response: AxiosResponse<ResponseData>) => {
    if (response.data.code === 200) {
      return Promise.resolve(response);
    }
    return Promise.reject(response);
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

export default service;
